<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '商品列表',
  },
}
</route>

<template>
  <page-meta :page-style="`overflow:${state.dropMenuShow ? 'hidden' : 'visible'};`"></page-meta>

  <view>
    <htm-popup />
    <wd-popup
      v-model="state.show"
      position="right"
      custom-style="width: 550rpx;"
      @click-modal="handleModal"
      :close-on-click-modal="false"
    >
      <view class="mt-5">
        <text class="ml-5">状态</text>
        <wd-checkbox-group v-model="state.query.status" cell shape="button">
          <wd-checkbox
            :modelValue="status"
            v-for="(status, index) in state.statusList"
            :key="index"
          >
            {{ status }}
          </wd-checkbox>
        </wd-checkbox-group>
        <text class="ml-5">标签</text>
        <wd-checkbox-group v-model="state.query.tags" cell shape="button">
          <wd-checkbox :modelValue="tag" v-for="(tag, index) in state.tagsList" :key="index">
            {{ tag }}
          </wd-checkbox>
        </wd-checkbox-group>
      </view>
      <view class="!flex justify-around absolute bottom-5 w-full">
        <htm-button @click="handleCancel('popup')" plain type="info">清除</htm-button>
        <htm-button custom-class="!ml-2" @click="handleConfirm('popup')">确认</htm-button>
      </view>
    </wd-popup>
    <wd-sticky>
      <wd-search
        custom-style="box-sizing: border-box; width: 100vw; height: 100rpx; margin-bottom: -8rpx"
        v-model="state.query.upcCode"
        placeholder-left
        hide-cancel
        @search="handleSearch()"
      />
      <!-- <htm-popup /> -->
      <view class="detail-top">
        <wd-drop-menu
          custom-style="flex: 1"
          @opened="() => (state.dropMenuShow = true)"
          @closed="() => (state.dropMenuShow = false)"
        >
          <wd-drop-menu-item
            v-model="state.query.sortRule"
            :options="state.sortRules"
            @close="handleConfirm('')"
          />
          <wd-drop-menu-item :title="state.categorieTitle" ref="categorieDropMenu">
            <view class="detail-menu">
              <scroll-view scroll-y class="detail-scroll-view">
                <wd-radio-group
                  v-model="state.categoryId"
                  cell
                  v-if="state.categoryType === 1"
                  @change="({ value }) => handleChange(value)"
                >
                  <wd-radio
                    v-for="(item, index) in state.categories.filter((x) => x.level === 1)"
                    :key="index"
                    :value="item.id"
                  >
                    {{ item.type_desc }}
                  </wd-radio>
                </wd-radio-group>
                <view class="wraper" v-if="state.categoryType === 2">
                  <htm-sidebar
                    custom-style="font-size: 24rpx"
                    v-model="state.categoryId"
                    @change="({ value }) => handleChange(value)"
                  >
                    <htm-sidebar-item
                      v-for="(item, index) in state.categories.filter((x) => x.level === 1)"
                      :value="item.id"
                      :key="index"
                      :label="item.type_desc"
                    />
                  </htm-sidebar>
                  <view class="content">
                    <scroll-view
                      scroll-y
                      scroll-with-animation
                      :show-scrollbar="false"
                      :scroll-top="scrollTop"
                      :throttle="false"
                    >
                      <wd-radio-group v-model="state.categoryChildId" cell>
                        <wd-radio
                          v-for="(item, index) in state.categories.filter(
                            (x) => x.p_id === state.categoryId,
                          )"
                          :key="index"
                          :value="item.id"
                        >
                          {{ item.type_desc }}
                        </wd-radio>
                      </wd-radio-group>
                    </scroll-view>
                  </view>
                </view>
              </scroll-view>
              <view class="detail-button">
                <htm-button
                  custom-style="width: 45vw"
                  @click="handleCancel('categorie')"
                  plain
                  type="info"
                >
                  清除
                </htm-button>
                <htm-button custom-style="width: 45vw" @click="handleConfirm('categorie')">
                  确认
                </htm-button>
              </view>
            </view>
          </wd-drop-menu-item>
          <wd-drop-menu-item :title="state.brandTitle" ref="brandDropMenu">
            <view class="detail-menu">
              <scroll-view scroll-y class="detail-scroll-view">
                <wd-radio-group v-model="state.query.brandName" cell shape="button">
                  <wd-radio v-for="(item, index) in state.brands" :key="index" :value="item.label">
                    {{ item.label }}
                  </wd-radio>
                </wd-radio-group>
              </scroll-view>
              <view class="detail-button">
                <htm-button
                  custom-style="width: 45vw"
                  @click="handleCancel('brand')"
                  plain
                  type="info"
                >
                  清除
                </htm-button>
                <htm-button custom-style="width: 45vw" @click="handleConfirm('brand')">
                  确认
                </htm-button>
              </view>
            </view>
          </wd-drop-menu-item>
        </wd-drop-menu>
        <view class="detail-filter">
          <wd-divider vertical />
          <htm-button
            custom-style="margin-left: 5rpx;color: black;"
            type="text"
            @click="handleFilter"
          >
            筛选
            <wd-icon name="filter" size="20rpx"></wd-icon>
          </htm-button>
        </view>
      </view>
    </wd-sticky>
    <view style="margin-top: -8rpx"></view>
    <htm-card
      v-for="item in state.productList"
      :key="item.id"
      direction="horizontal"
      v-bind="item"
    />
    <wd-loadmore :state="state.loadmoreState" finished-text="没有更多了" @reload="handleReload" />
  </view>
</template>

<script lang="ts" setup>
import htmSidebar from '@/components/htm-sidebar/htm-sidebar.vue'
import htmSidebarItem from '@/components/htm-sidebar-item/htm-sidebar-item.vue'
import htmCard from '@/components/htm-card/htm-card.vue'
import htmPopup from '@/components/htm-popup/htm-popup.vue'
import {
  getQueryCondition,
  IBrand,
  ICategory,
  IProductQueryParams,
  IProductQueryResult,
  IQueryConditionResult,
  ISortRule,
  productQuery,
} from '@/service/detail/detail'
import { IProductResult } from '@/service/index'
const scrollTop = ref<number>(0)
const state = reactive({
  sortRules: [] as Record<string, any>[],
  categories: [
    {
      id: '',
      level: 1,
      p_id: '0',
      type_desc: '全部商品',
    },
  ] as ICategory[],
  categorieTitle: '',
  brands: [] as Record<string, any>[],
  brandTitle: '',
  show: false,
  tagsList: [] as string[],
  statusList: [] as string[],
  query: {
    brandName: '',
    categoryId: '',
    sortRule: '',
    upcCode: '',
    status: [],
    tags: [],
    pageNo: 1,
    pageSize: 15,
  } as IProductQueryParams,
  result: {} as IProductQueryResult,
  productList: [] as IProductResult[],
  loadmoreState: 'loading' as any,
  categoryType: 1,
  categoryId: '',
  categoryChildId: '',
  dropMenuShow: false,
})

const categorieDropMenu = ref()
const brandDropMenu = ref()
let status: string[] = []
let tag: string[] = []

const getProductList = async () => {
  const {
    loading: loadingProductQuery,
    data: productQueryData,
    run: runProductQuery,
  } = useRequest<IProductQueryResult>(() => productQuery(state.query))
  const data = await runProductQuery()
  state.result = data
  state.productList = [...state.productList, ...data.records]
  if (state.query.pageNo >= state.result.pages) {
    state.loadmoreState = 'finished'
  }
}
const handleConfirm = async (type) => {
  if (type === 'categorie') {
    if (!state.categoryChildId) {
      const item = state.categories.filter((x) => x.id === state.categoryId)
      state.categorieTitle = item.length > 0 ? item[0].type_desc : ''
      state.query.categoryId = state.categoryId
    }
    if (state.categoryChildId) {
      const item = state.categories.filter((x) => x.id === state.categoryChildId)
      state.categorieTitle = item.length > 0 ? item[0].type_desc : ''
      state.query.categoryId = state.categoryChildId
    }
    categorieDropMenu.value.close()
  }
  if (type === 'brand') {
    state.brandTitle = state.query.brandName
    brandDropMenu.value.close()
  }
  if (type === 'popup') {
    state.show = false
  }
  state.productList = []
  state.loadmoreState = 'loading'
  await getProductList()
}

const handleCancel = (type) => {
  if (type === 'categorie') {
    state.categorieTitle = '全部分类'
    state.query.categoryId = ''
    state.categoryId = ''
    state.categoryChildId = ''
    state.categoryType = 1
    categorieDropMenu.value.close()
  }
  if (type === 'brand') {
    state.brandTitle = '全部品牌'
    state.query.brandName = ''
    brandDropMenu.value.close()
  }
  if (type === 'popup') {
    state.query.status = []
    state.query.tags = []
    state.show = false
  }
  state.productList = []
  state.loadmoreState = 'loading'
  getProductList()
}
const handleFilter = () => {
  status = state.query.status
  tag = state.query.tags
  state.show = true
}
const handleModal = () => {
  state.query.status = status
  state.query.tags = tag
  state.show = false
}

const handleSearch = async () => {
  state.productList = []
  state.loadmoreState = 'loading'
  await getProductList()
}

onLoad(async () => {
  const {
    loading: loadingQueryConditions,
    data: queryConditionData,
    run: runQueryConditions,
  } = useRequest<IQueryConditionResult>(() => getQueryCondition())
  const data = await runQueryConditions()
  data.sortRules.forEach((item: ISortRule) => {
    state.sortRules.push({
      label: item.sortLabel,
      value: item.sortField,
    })
  })
  data.categories.forEach((item: ICategory) => {
    state.categories.push(item)
  })
  data.brands.forEach((item: IBrand) => {
    state.brands.push({
      label: item.brandName,
      value: item.id,
    })
  })
  state.query.sortRule = data.sortRules[0].sortField
  state.categorieTitle = '全部分类'
  state.query.categoryId = ''
  state.brandTitle = '全部品牌'
  state.query.brandName = ''
  state.statusList = data.statusList
  state.tagsList = data.tags

  await getProductList()
})
onReachBottom(() => {
  if (state.query.pageNo < state.result.pages) {
    handleReload()
  } else if (state.query.pageNo === state.result.pages) {
    state.loadmoreState = 'finished'
  }
})

const handleReload = async () => {
  state.query.pageNo += 1
  state.loadmoreState = 'loading'
  await getProductList()
}

const handleChange = (value) => {
  const childs = state.categories.filter((x) => x.p_id === value)
  if (childs.length > 0) {
    state.categoryType = 2
    state.categoryChildId = ''
  } else {
    state.categoryType = 1
    state.categoryChildId = ''
  }
}
</script>

<style lang="scss" scoped>
@import '/src/style/index';
.detail-top {
  display: flex;
  align-items: center;
  width: 100vw;
  background-color: white;
  .detail-filter {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 160rpx;
  }
}
.detail-menu {
  height: 800rpx;
  .detail-scroll-view {
    height: 700rpx;
  }
  .detail-button {
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 100rpx;
  }
}
.wraper {
  display: flex;
  height: 700rpx;
  overflow: hidden;
}
.content {
  flex: 1;
  background: #fff;
  transition: transform 0.3s ease;
}
.category {
  box-sizing: border-box;
  height: 100%;
}
</style>
